import React, { forwardRef } from 'react';
import { TreeSelect } from 'antd';
import storage from '../../utils/storage';
const { TreeNode } = TreeSelect;

export default function DeptSelect(props) {
  const {
    treeCheckable, // 是否多选
    treeCheckStrictly, // 多选时是否取消父子关联, 为true时，每个value为对象
    deptTree, // 全部部门数据
    deptArr, // 当前部门数据
    hasRight, // 是否需要权限展示
    nodeDisabled, // 节点是否禁选的表达式
    disabled, // 新增，编辑，详情(禁选)
    style = {},
    className = '',
    layout = {
      className: 'tantuer-form-item2 tantuer-form-item-nowrap',
    },
    rules = [],
    name = 'dept_ids',
    onChange,
    maxHeight = 400, // 滚动高度
    form,
    defaultValue = null,
    placeholder = '请选择',
    needLable = true,
    options, // 其他参数
    allowClear = true
  } = props;

  const treeDisable = (item) => {
    if (treeCheckable) {
      let isAll = false;
      if (form) {
        const formValue = form.getFieldValue(name);
        isAll = formValue.includes(-1) || formValue.some((i) => i.value === -1);
      }
      return !isAll && item.dept_id === storage.dept;
    }
  };

  const TreeNodeRender = (parent) => {
    return parent.map((item) =>
      hasRight ? (
        (!item.dept_id || item.has_right) &&
        (item.child && item.child.length > 0 ? (
          <TreeNode
            value={item.dept_id || -1}
            title={item.dept_name}
            key={item.dept_id || -1}
            disabled={treeDisable(item) || (nodeDisabled ? nodeDisabled(item) : false)}
          >
            {TreeNodeRender(item.child)}
          </TreeNode>
        ) : (
          <TreeNode disabled={treeDisable(item)} value={item.dept_id} title={item.dept_name} key={item.dept_id} />
        ))
      ) : item.child && item.child.length > 0 ? (
        <TreeNode
          value={item.dept_id || -1}
          title={item.dept_name}
          key={item.dept_id || -1}
          disabled={treeDisable(item) || (nodeDisabled ? nodeDisabled(item) : false)}
        >
          {TreeNodeRender(item.child)}
        </TreeNode>
      ) : (
        <TreeNode disabled={treeDisable(item)} value={item.dept_id} title={item.dept_name} key={item.dept_id} />
      )
    );
  };

  const renderDeptValue = () => {
    if (!deptArr || (deptArr.ids ? deptArr.ids.length === 0 : deptArr.length === 0)) {
      return defaultValueInit();
    }
    if (treeCheckStrictly) {
      let deptValue = [];
      deptArr &&
        deptArr.ids &&
        deptArr.ids.forEach((item, index) => {
          let data = {
            label: deptArr.name[index],
            value: deptArr.ids[index],
          };
          deptValue.push(data);
        });
      return deptValue;
    } else {
      return deptArr || undefined;
    }
  };

  const defaultValueInit = () => {
    if (defaultValue) {
      return defaultValue;
    } else {
      if (treeCheckStrictly) {
        return [
          {
            lable: '全部部门',
            value: -1,
          },
        ];
      }
    }
    return undefined;
  };

  const selectChange = (value) => {
    if (Array.isArray(value)) {
      let newData = [];
      if (value.length > 0) {
        if (treeCheckStrictly) {
          // 全部部门与其它部门互斥
          if (value[value.length - 1].value === -1) {
            newData = [{ label: deptTree[0].dept_name, value: -1 }];
          } else if (value[0].value === -1) {
            newData = value.slice(1);
          }
        } else {
          if (value[value.length - 1] === -1) {
            newData = [-1];
          } else if (value[0] === -1) {
            newData = value.splice(0, 1);
          }
        }
      }
      const deptValue = treeCheckStrictly ? { label: '', value: storage.dept } : storage.dept;
      let temp = [deptValue],
        newValue = [];
      if (
        newData.find((x) => x.value === -1) ||
        newData.includes(-1) ||
        value.find((x) => x.value === storage.dept) ||
        value.includes(storage.dept)
      ) {
        temp = [];
      }

      if (newData.length > 0) {
        newValue = [...newData, ...temp];
      } else {
        newValue = [...value, ...temp];
      }
      setTimeout(() => onChange && onChange(newValue));
      return newValue;
    } else {
      setTimeout(() => onChange && onChange(value));
      return value;
    }
  };

  const RenderTreeSelect = forwardRef((props, ref) => {
    const onSelect = (value) => {
      const selectValue = selectChange(value);
      props.onChange(selectValue);
    };
    return (
      <TreeSelect
        {...props}
        ref={ref}
        style={{ width: '100%', ...style }}
        placeholder={placeholder}
        allowClear={allowClear}
        treeCheckable={treeCheckable || false}
        disabled={disabled}
        treeCheckStrictly={treeCheckStrictly || false}
        onChange={onSelect}
        className={className}
        dropdownStyle={{ maxHeight }}
        showSearch
        treeNodeFilterProp='title'
        maxTagCount={20}
        {...options}
      >
        {TreeNodeRender(deptTree)}
      </TreeSelect>
    );
  });

  return {
    label: needLable && {
      label: '可见部门',
      ...layout,
    },
    name: name,
    options: {
      initialValue: renderDeptValue(),
      rules,
    },
    component: <RenderTreeSelect />,
  };
}
